import { useState } from "react";
import { Popover, Tooltip, Modal, Button, Typography } from "antd";
import { isEmpty, find, cloneDeep } from 'lodash';
import IconFont from "@/components/IconFont";
import { getDecryptionAddressOp, decryptLogUpload } from "../../../../../services";
import {
	queryTopToken,
	orderStatusVirtualNumber,
	virtualNumberExtension,
} from '@/services/common';
import moment from 'moment';

//地址渲染Icon
const iconStyle = {
	marginLeft: '4px',
	cursor: 'pointer'
}

const { Paragraph } = Typography;

//地址渲染
export default function AddressRender(props) {
	const { handleModalOpera, record } = props;

	const [loading, setLoading] = useState(false);

	const [realAddressData, setRealAddressData] = useState({}); //解密之后的地址

	//淘宝的解密数据
	const [decryptData, setDecryptData] = useState([]);

	//揭秘要用的场景id
	const [sceneData, setSceneData] = useState({});

	//点击地址解密
	const handleRenderRealAddress = (val, reocrd) => {
		if (val) {
			const obj = find(reocrd.deliveryInfoList, (item => item.type == 1 && item.isPlaintext == 1));
			if (!isEmpty(obj)) { //列表返回存在解密无需调接口
				setRealAddressData(obj);
			} else {
				if (reocrd.orderChannel == 8 || reocrd.orderChannel == 18) { //淘宝天猫解密
					renderDecryptData(record.ecStoreId, record.goodsList[0].outOrderSn)
				} else { //非淘宝
					renderRealAddress();
				}
			}
		} else {
			setRealAddressData({});
			setDecryptData([]);
		}
	}

	//点击查看详细地址信息
	const renderRealAddress = async () => {
		setLoading(true);
		const { success, data = {} } = await getDecryptionAddressOp({
			id: record.id,
		});
		if (success) {
			setRealAddressData(data);
		}
		setLoading(false);
	};

	//淘宝获取解密后的数据
	const renderDecryptData = (ecStoreId, outOrderSn) => {
		const model = localStorage.getItem('model');
		const secToken = window.secToken;
		//获取token
		const p1 = new Promise(async (resolve, reject) => {
			const { data = {}, success } = await queryTopToken({
				ecStoreId,
				model,
			});
			if (success) {
				resolve(data);
			} else {
				reject('网络请求错误');
			}
		});
		// 判断订单状态虚拟号用
		const p2 = new Promise(async (resolve, reject) => {
			const { data = {}, success } = await orderStatusVirtualNumber({
				orderSn: outOrderSn?.split(',')?.[0],
				sotreId: ecStoreId,
			});
			if (success) {
				resolve(data);
			} else {
				reject('网络请求错误');
			}
		});
		Promise.all([p1, p2]).then((arr) => {
			const [data1, data2] = arr;
			setSceneData(data2);
			secToken
				.getTopDataByBX({
					params: Object.assign(data1, {
						secToken: model,
						method: 'taobao.top.oaid.client.decrypt',
					}),
					headers: {
						'Content-Type': 'Application/x-www-form-urlencoded',
					},
					data: `query_list={"tid": "${outOrderSn.split(',')[0]}","oaid": "${data2.oaid
						}","scene":"${data2.scene}", "secret_no_days":"${data2.secretNoDays
						}"}`,
				})
				.then(({ receiver_list = [], request_id, error_response = {} }) => {
					if (receiver_list.length > 0) {
						setDecryptData(receiver_list);
						//前端解密完成上传日志
						decryptLogUpload({
							action: '1007',
							orderSn: outOrderSn,
							topRequestId: request_id,
						});
					} else {
						if (Object.keys(error_response).length > 0) {
							//解密失败的提示
							const { sub_msg = '' } = error_response;
							Modal.info({
								content: sub_msg,
							});
						}
						setDecryptData([]);
					}
				});
		});
	};

	//鼠标划过查看地址详情
	const renderAddressContent = (record) => {
		if (!loading) {
			if (!isEmpty(realAddressData)) {
				const { name, phone, province, city, district, street, address } = realAddressData;
				const text = `${name} ${phone} ${province} ${city} ${district} ${street != null ? street: ''} ${address} `;
				return <div style={{ width: "240px" }}>{text}</div>;
			} else if (!isEmpty(decryptData)) {
				const obj = decryptData[0];
				const addressObj = find(record.deliveryInfoList, (item => item.type == 2));
				return (
					<div className="custom-ant-popver-content">
						<div
							style={{
								borderBottom: '1px dotted #ccc',
								paddingBottom: '12px',
								marginBottom: '12px',
							}}
						>
							<span style={{ fontWeight: '600', color: '#000' }}>
								针对<span className="common-color9">虚拟号</span>订单
							</span>
							，手机号会展示11位主机号+4位分机号，示例：15912344321-4567，可直接用于打单发货、联系买家，先拨打虚拟号11位主机号，并根据语音提示输入4位分机号,
							该虚拟号会在消费者签收后若干天失效虚拟号到期时间：
							{obj.secret_no_expire_time}
							{moment(obj.secret_no_expire_time).valueOf() <
								moment(new Date()).valueOf() ? (
								<>
									<span style={{ marginRight: '16px' }} className="common-color9">
										(已过期)
									</span>
								</>
							) : (
								''
							)}
							<Button
								onClick={() => handleVirtualNumberExtension(record)}
								size="small"
								type="primary"
							>
								更新虚拟号
							</Button>
						</div>
						<Paragraph
							copyable={{
								text: `${obj.name ? obj.name + ' ' : ''} ${obj.mobile ? obj.mobile + ' ' : ''
									} ${obj.state ? obj.state + ' ' : ''}${obj.city ? obj.city + ' ' : ''
									}${obj.district ? obj.district + ' ' : ''}${obj.address_detail
										? obj.address_detail + ' '
										: addressObj.address
											? addressObj.address
											: ''
									}`,
								tooltips: false,
							}}
							style={{ marginBottom: 0 }}
						>
							<span style={{ marginLeft: 5 }}>
								{obj.name ? obj.name + ' ' : ''}{' '}
								{obj.mobile ? obj.mobile + ' ' : ''}{' '}
							</span>
							<span>
								{obj.state ? obj.state + ' ' : ''}
								{obj.city ? obj.city + ' ' : ''}
								{obj.district ? obj.district + ' ' : ''}
								{obj.address_detail
									? obj.address_detail + ' '
									: addressObj.address
										? addressObj.address
										: ''}
							</span>
						</Paragraph>
					</div>
				)
			} else {
				return <div className="custom-ant-popver-content">地址解密</div>;
			}
		} else {
			return <div style={{ width: "240px" }}>数据加载中...</div>;
		}
	};

	//更新虚拟号
	const handleVirtualNumberExtension = async (record) => {
		setLoading(true);
		const list = cloneDeep(decryptData);
		const newObj = list[0];
		const { success, data = {} } = await virtualNumberExtension({
			scene: sceneData.scene,
			orderSn: record.goodsList[0].outOrderSn,
			sotreId: record.ecStoreId,
			oaid: sceneData.oaid,
		});
		if (success) {
			newObj.secret_no_expire_time = data.expireTime;
			newObj.mobile = data.secretNo;
			setDecryptData(list);
		}
		setLoading(false);
	};

	return (
		record.deliveryInfoList.map((v, index) => {
			if (v.type == 2) {
				const { name, phone, province, city, district, address, street, errorFlag } = v;	//地址信息
				const addressInfo = `${name} ${phone} ${province} ${city} ${district} ${street ? street: ''} ${address}`;
				return (
					<div key={index}>
						{errorFlag && errorFlag == 1 ? (
							<Tooltip title="该订单收货信息有误，需要修改">
								<span style={{ marginRight: '4px' }}>
									<IconFont style={{ fontSize: '14px', cursor: 'pointer'}} type="icongantanhao" />
								</span>
							</Tooltip>
						) : null}
						{addressInfo}
						{[10, 30].includes(record['state']) && ![9].includes(record.orderChannel) && (
							<IconFont type="iconbianji1-copy" style={iconStyle} onClick={() => handleModalOpera('updateAddress', record)} />
						)}
						<Popover trigger="click" content={renderAddressContent(record)} onOpenChange={val => handleRenderRealAddress(val, record)}>
							<IconFont type="iconzhengyan" style={iconStyle} />
						</Popover >
					</div>
				)
			}
		})
	)
}